/**
 * request 网络请求工具
 * 更详细的 api 文档: https://github.com/umijs/umi-request
 */
import { message, notification } from 'antd'
import qs from 'qs'
import type { ResponseError } from 'umi-request'
import { extend } from 'umi-request'
import parse from 'url-parse'

let apiHost = ''
let goApiHost = ''
const host = window.location.hostname
// const host = 'ince.preview.n2.ltd'
// const hostMappings = {
//    localhost: 'http://8.130.96.173:8088'
// }
apiHost = 'http://8.130.96.173:8088'
// if (hostMappings[host] === undefined) {
//   // apiHost = 'http://vcapi.staging.internal.n2boost.com'
//   // goApiHost = 'http://vcapi.staging.internal.n2boost.com'
//   // apiHost = 'http://192.168.2.164:9501'
//   // goApiHost = 'http://192.168.2.164:9511'
// } else {
//   goApiHost = hostMappings[host + '_goapi']
//   apiHost = hostMappings[host]
// }
// if (!goApiHost) {
//   goApiHost = apiHost
// }
export { apiHost, goApiHost }

const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '需要授权以继续访问资源',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
}

/**
 * 异常处理程序
 */
/* eslint-disable no-throw-literal */
const errorHandler = (error: ResponseError): Response => {
  const { response } = error
  if (response && response.status) {
    const errorText = codeMessage[response.status] || response.statusText
    const { status, url } = response

    if (status === 401) {
      window.location.href = '/user/login'
      return response
      // notification.error({
      //   message: `登录过期，需重新授权`,
      //   description: errorText,
      // })
    }
    notification.error({
      message: `请求错误 ${status}: ${url}`,
      description: errorText,
    })
  } else if (!response) {
    notification.error({
      description: '您的网络发生异常，无法连接服务器',
      message: '网络异常',
    })
  }
  throw error
  // throw error
  // return response
}

const accessToken = localStorage.getItem('access_token')
const headers = {}
if (accessToken) {
  headers.Authorization = `Bearer ${accessToken}`
}

/**
 * 配置request请求时的默认参数
 */
const request = extend({
  errorHandler, // 默认错误处理
  headers,
  credentials: 'include', // 默认请求是否带上cookie
  paramsSerializer(params) {
    return qs.stringify(params)
  },
})

// 提前对响应做异常处理
// request.interceptors.response.use(async (response) => {
//   const data = await response.json();
//   if (!data.success) {
//     message.error(data.message)
//   }
//   return response;
// });

request.interceptors.request.use((url, options) => {
  const parsed = parse(url)
  const parsedApi = parse(apiHost)
  const parsedGoApi = parse(goApiHost)
  if (!url.startsWith('http')) {
    if (url.includes('goapi')) {
      parsed.set('host', parsedGoApi.host)
      parsed.set('protocol', parsedGoApi.protocol)
    } else {
      parsed.set('host', parsedApi.host)
      parsed.set('protocol', parsedApi.protocol)
    }
  }
  return {
    url: parsed.href,
    options,
  }
})

request.use(async (ctx, next) => {
  await next()

  const { res } = ctx
  if (res.success === false && res.message !== undefined) {
    message.destroy()
    message.error(res.message)
    if (res.code === 5300) {
      localStorage.removeItem('access_token')
      location.href = '/bootstrap/license'
    }
  }
})

export default request
